<template>
    <div>
        <!--  搜索框部分-->
        <div class="demo-input-size">
            <!--    搜索模式-->
            <el-select v-model="searchMode" placeholder="请选择" style="width: 150px;margin-right: 10px">
                <el-option value="id" label="用户id"></el-option>
                <el-option value="username" label="账号"></el-option>
                <el-option value="nickname" label="昵称"></el-option>
            </el-select>
<!--            根据搜索模式动态 加载相应的输入框-->
            <el-input v-if="searchMode==='id'" placeholder="请输入用户id" prefix-icon="el-icon-search" style="width: 250px;padding-right: 5px" v-model="searchParams.id"></el-input>
            <el-input v-if="searchMode==='nickname'" placeholder="请输入昵称" prefix-icon="el-icon-search" style="width: 250px;padding-right: 5px" v-model="searchParams.nickname"></el-input>
            <el-input v-if="searchMode==='username'" placeholder="请输入账号" prefix-icon="el-icon-search" style="width: 250px;padding-right: 5px" v-model="searchParams.username"></el-input>

            <el-button type="primary" @click="search">搜索</el-button>
            <el-button type="danger" @click="reload">重置</el-button>

        </div>
        <!--          按钮栏-->
        <div style="padding-top: 10px">
            <el-button type="primary" @click="handleAdd"><i class="el-icon-circle-plus" style="padding-right: 6px"></i>新增</el-button>
            <el-button type="danger" @click="delBatch"><i class="el-icon-remove" style="padding-right: 6px"></i>批量删除</el-button>
        </div>
<!--        表格-->
        <el-table :data="tableData" background-color="black" @selection-change="handleSelectionChange">
<!--      @selection-change      用于监听用户的选择操作。当用户在表格中选择或取消选择行数据时，这个事件会被触发。-->
            <el-table-column type="selection" ></el-table-column>
            <el-table-column prop="id" label="id" width="100" ></el-table-column>
            <el-table-column prop="username" label="账号" width="150" ></el-table-column>
            <el-table-column label="身份" width="150" >
                <template slot-scope="scope">
                    <span v-if="scope.row.role==='user'">用户</span>
                    <span v-if="scope.row.role==='vip'">会员</span>
                    <span v-if="scope.row.role==='admin'">管理员</span>
                </template>
            </el-table-column>
            <el-table-column prop="nickname" label="昵称" width="180" ></el-table-column>
            <el-table-column prop="phone" label="电话" width="180" ></el-table-column>
            <el-table-column prop="email" label="邮箱" width="180" ></el-table-column>
            <el-table-column prop="address" label="地址" width="350" ></el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            type="success"
                            @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button
                            size="mini"
                            type="danger"
                            @click="handleDelete(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--  显示分页组件-->
        <div class="block" style="flex: 0 0 auto">
            <!--    属性绑定，将组件的currentPage pageSize等绑定到分页组件上-->
            <!-- size-change监听页数选择器  当用户切换到不同的页数时，调用方法 下一个监听当前页-->
            <el-pagination
                    :current-page="currentPage"
                    :page-sizes="[3, 5, 8, 10]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentPage"
            >
            </el-pagination>
        </div>
<!--        编辑的弹窗-->
        <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
            <el-form :model="user" label-width="70px" :rules="rules" ref="userForm" style="padding: 0 60px">
<!--                与user进行双向绑定编辑的信息传进去-->
                <el-form-item label="账号" prop="username">
                    <el-input v-model="user.username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="user.password" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="user.nickname" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="身份" prop="role">
                    <el-select v-model="user.role" placeholder="请选择">
                        <el-option
                                v-for="item in roleOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                    <el-input v-model="user.phone" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="user.email" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="地址" prop="address" >
                    <el-input v-model="user.address" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    export default {
        name: "User",
        created() {
            this.load()
        //    一些初始化加载  获取数据
        },
        data(){
            return{
                searchMode:'id',
                searchParams:{
                    id: '',
                    username: '',
                    nickname: ''
                },
                tableData: [],
                total: 0,
                currentPage: 1,
                pageSize:5,
                dialogTitle:'',
                rules: {
                    username: [
                        { required: true, message: '请输入账号', trigger: 'blur' },
                        {min: 3, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
                    ],password: [
                        { required: true, message: '请输入密码', trigger: 'blur'}
                    ],nickname: [
                        { required: true, message: '请输入昵称', trigger: 'blur'},
                        {min: 3, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
                    ],role: [
                        { required: true, message: '请选择身份', trigger: 'change'}
                    ],email: [
                        { required: true, message: '请输入邮箱', trigger: 'blur'},
                    ],address: [
                        { required: true, message: '请输入地址', trigger: 'blur'}
                    ],phone: [
                        { required: true, message: '请输入电话', trigger: 'blur'},
                        { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }

                    ]
                },
                user: {},
                roleOptions: [{
                    value: 'admin',
                    label: '管理员'
                },{
                    value: 'vip',
                    label: '会员'
                }, {
                    value: 'user',
                    label: '用户'
                },
                ],
                dialogFormVisible:false,
            //    编辑弹窗的显示
                multipleSelection: [],
            //    一个数组，记录批量删除中的选中了多少

            }
        },
        methods:{
            //从后端获取用户数据，根据响应更新前端表格中的数据和分页信息
            load(){
                this.request.get("/user/page",{
                    //第二个参数是一个对象
                    params:{
                        pageNum: this.currentPage,//页码
                        pageSize: this.pageSize,//每页显示的数量
                        id: this.searchParams.id,
                        username: this.searchParams.username,
                        nickname: this.searchParams.nickname
                    }
                }).then(res=>{
                        if(res.code==='200'){
                            this.tableData = res.data.records;
                            this.total = res.data.total;//赋值，用于计算总页数和总条目数
                        }

                    }
                )
            },
            //当用户选择不用的每页显示数量时，被触发
            handleSizeChange(pageSize){
                this.pageSize = pageSize;
                this.load();//调用方法重新加载对应页的数量
            },
            //切换到不同的页码时
            handleCurrentPage(currentPage){
                this.currentPage = currentPage;
                this.load();
            },
            //当用户选择或者取消表格中的行时
            handleSelectionChange(val){
                console.log("val:",val)
                //用于监听用户在表格中选择或者取消选择行，将选中行的数据保存在this.multiple..中
                this.multipleSelection = val
            //    用于批量删除
            },

            //删除
            handleDelete(id){
                this.$confirm('确认删除该用户吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.request.delete("/user/"+id).then(res=>{
                        if(res.code==='200'){
                            this.$message({
                                type: "success",
                                message: "删除成功",
                            });
                            this.load();
                        }else {
                            this.$message.error(res.msg);
                        }
                    })
                })
            },
            //编辑
            handleEdit(row){
                this.user = JSON.parse(JSON.stringify(row));
                this.dialogTitle='编辑用户';
                this.dialogFormVisible = true;
            },

            //在提交用户信息表单之前对表单进行验证
            //validate是组件提供的验证方法，根据校验规则进行验证
            submitForm() {
                this.$refs.userForm.validate(valid => {
                    if (valid) {
                        // 表单验证通过，执行保存操作
                        this.save();
                    } else {
                        // 表单验证失败，显示错误提示或其他操作
                        this.$message.error('请检查输入的数据');
                    }
                });
            },
            //插入或修改
            save(){
                this.dialogTitle='新增用户'
                this.request.post("/user",this.user).then(res=>{
                    if(res.code==='200'){
                        this.$message.success("保存成功");
                        this.dialogFormVisible = false;
                        this.load();
                    }else{
                        this.$message.error(res.msg)
                    }
                })
            },
            handleAdd(){
                this.dialogTitle='新增用户'
                this.dialogFormVisible = true;
                this.user = {};

            },
            //批量删除
            delBatch(){
                let ids = this.multipleSelection.map(v => v.id);
                //创建新数组，存储了mul..数组中每个元素id的值，用于进行批量操作
                console.log(ids);
                this.$confirm('确认删除这些用户吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //调用后端
                    this.request.post("/user/del/batch",ids).then(res=>{
                        if(res.code==='200'){
                            this.$message({
                                type: "success",
                                message: "删除成功",
                                duration: 3000
                            });
                            this.load();
                        }else {
                            this.$message.error(res.msg);
                        }
                    })

                })

            },
            search(){
                this.currentPage = 1;
                //将当前页码设置为1，以确保搜索结果从第一页开始显示
                this.load();
                //  加载搜索结果数据
            },
        //    重置
            reload(){
                this.searchParams.id='';
                this.searchParams.username='';
                this.searchParams.nickname='';
                this.load()
            },


        },

    }
</script>

<style scoped>

</style>